package com.eltonkent.dashboard.service.responsehandler;

import java.io.IOException;
import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.eltonkent.dashboard.data.container.GeoCodeContainer;

public class YahooReverseCodeHandler extends XmlHandler {

	private static final String NODE_STATUS = "Error";
	private static final String NODE_ADDRESS_LINE1 = "line1";
	private static final String NODE_ADDRESS_LINE2 = "line2";
	private static final String NODE_ADDRESS_LINE3 = "line3";

	private static final String NODE_COUNTRY_NAME = "country";
	private static final String NODE_LOCALITY_NAME = "county";
	private static final String NODE_POSTALCODE = "postal";
	private static final String NODE_WOEID = "woeid";

	@Override
	public GeoCodeContainer deserialize(InputStream is) {
		try {
			XmlPullParser parser = getParser(is);
			int eventType = parser.getEventType();
			String tagName;
			GeoCodeContainer container = new GeoCodeContainer();
			for (; eventType != XmlPullParser.END_DOCUMENT;) {
				if (eventType == XmlPullParser.START_TAG) {
					tagName = parser.getName();
					if (tagName.equals(NODE_STATUS)) {
						eventType = parser.next();
						if (eventType == XmlPullParser.TEXT)
							container.setStatusCode(parser.getText());
					} else if (tagName.equals(NODE_ADDRESS_LINE1)) {
						eventType = parser.next();
						if (eventType == XmlPullParser.TEXT)
							container.setAddressLine1(parser.getText());
					} else if (tagName.equals(NODE_ADDRESS_LINE2)) {
						eventType = parser.next();
						if (eventType == XmlPullParser.TEXT)
							container.setAddressLine2(parser.getText());
					} else if (tagName.equals(NODE_ADDRESS_LINE3)) {
						eventType = parser.next();
						if (eventType == XmlPullParser.TEXT)
							container.setAddressLine3(parser.getText());
					} else if (tagName.equals(NODE_COUNTRY_NAME)) {
						eventType = parser.next();
						if (eventType == XmlPullParser.TEXT)
							container.setCountryName(parser.getText());
					} else if (tagName.equals(NODE_LOCALITY_NAME)) {
						eventType = parser.next();
						if (eventType == XmlPullParser.TEXT)
							container.setLocalityName(parser.getText());
					} else if (tagName.equals(NODE_POSTALCODE)) {
						eventType = parser.next();
						if (eventType == XmlPullParser.TEXT)
							container.setPostalCodeNumber(parser.getText());
					} else if (tagName.equals(NODE_WOEID)) {
						eventType = parser.next();
						if (eventType == XmlPullParser.TEXT){
							container.setWoeid(parser.getText());
							break;
						}
					}
				}
				eventType = parser.next();
			}
			is.close();
			return container;
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
